<template>
  <el-dialog
    v-model="visible"
    title="选择缺陷"
    width="1200px"
    :before-close="handleClose"
    class="defect-selector-dialog"
    destroy-on-close
  >
    <div class="dialog-content">
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索缺陷标题..."
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filterStatus"
              placeholder="状态筛选"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filterPriority"
              placeholder="优先级筛选"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="option in priorityOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="loadDefects">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 缺陷列表 -->
      <div class="defect-list">
        <el-table
          ref="defectTableRef"
          v-loading="loading"
          :data="filteredDefects"
          height="500"
          @selection-change="handleSelectionChange"
          stripe
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="缺陷标题" min-width="250">
            <template #default="{ row }">
              <div class="defect-title">
                <span>{{ row.title }}</span>
                <el-tag
                  v-if="row.type"
                  :type="getDefectTypeTagType(row.type)"
                  size="small"
                  class="ml-2"
                >
                  {{ getDefectTypeLabelHelper(row.type) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="110">
            <template #default="{ row }">
              <el-tag v-if="row.status" :type="getStatusTagType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
              <span v-else class="text-gray-400">—</span>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="110">
            <template #default="{ row }">
              <el-tag v-if="row.priority" :type="getPriorityTagType(row.priority)" size="small">
                {{ getPriorityLabel(row.priority) }}
              </el-tag>
              <span v-else class="text-gray-400">—</span>
            </template>
          </el-table-column>
          <el-table-column prop="severity" label="严重程度" width="110">
            <template #default="{ row }">
              <el-tag v-if="row.severity" :type="getSeverityTagType(row.severity)" size="small">
                {{ getSeverityLabel(row.severity) }}
              </el-tag>
              <span v-else class="text-gray-400">—</span>
            </template>
          </el-table-column>
          <el-table-column prop="assignee_name" label="负责人" width="130" />
          <el-table-column prop="project_name" label="所属项目" width="180" />
          <el-table-column prop="found_date" label="发现日期" width="130">
            <template #default="{ row }">
              <span v-if="row.found_date">
                {{ formatDate(row.found_date) }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 已选择的缺陷 -->
      <div v-if="selectedDefects.length > 0" class="selected-section">
        <div class="selected-header">
          <span>已选择 {{ selectedDefects.length }} 个缺陷</span>
          <el-button type="text" @click="clearSelection">清空选择</el-button>
        </div>
        <div class="selected-list">
          <el-tag
            v-for="defect in selectedDefects"
            :key="defect.id"
            closable
            @close="removeDefect(defect)"
            class="selected-tag"
          >
            {{ defect.title }}
          </el-tag>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :disabled="selectedDefects.length === 0"
          @click="handleConfirm"
        >
          确定 ({{ selectedDefects.length }})
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getDefects, type Defect, type DefectFilter } from '@/api/defect'
import { getDefectStatusLabel, getDefectPriorityLabel, getDefectSeverityLabel, getDefectTypeLabel } from '@/types/defect'
import { useStateStore } from '@/stores/state'
import { priorityApi } from '@/api/priority'
import { ModuleType } from '@/types/core'

interface Props {
  modelValue: boolean
  projectId?: string
  versionIds?: string[]
  selectedDefectIds?: string[]
  excludeDefectIds?: string[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', defects: Defect[]): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  projectId: '',
  versionIds: () => [],
  selectedDefectIds: () => [],
  excludeDefectIds: () => []
})

const emit = defineEmits<Emits>()

// 状态管理
const stateStore = useStateStore()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const defects = ref<Defect[]>([])
const selectedDefects = ref<Defect[]>([])
const searchQuery = ref('')
const filterStatus = ref('')
const filterPriority = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 状态和优先级选项
const statusOptions = ref<Array<{value: string, label: string}>>([])
const priorityOptions = ref<Array<{value: string, label: string}>>([])

const defectTableRef = ref()

// 计算属性
const filteredDefects = computed(() => {
  let result = defects.value
  
  // 排除已关联的缺陷
  if (props.excludeDefectIds && props.excludeDefectIds.length > 0) {
    const excludeSet = new Set(props.excludeDefectIds)
    result = result.filter(defect => !excludeSet.has(defect.id))
  }
  
  if (searchQuery.value) {
    result = result.filter(defect => 
      defect.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  if (filterStatus.value) {
    result = result.filter(defect => defect.status === filterStatus.value)
  }
  
  if (filterPriority.value) {
    result = result.filter(defect => defect.priority === filterPriority.value)
  }
  
  return result
})

// 加载状态选项
const loadStatusOptions = async () => {
  try {
    await stateStore.fetchStates({ module_type: ModuleType.DEFECT })
    const defectStates = stateStore.getStatesByModule(ModuleType.DEFECT)
    statusOptions.value = defectStates.map(state => ({
      value: state.code,
      label: state.name
    }))
  } catch (error) {
    console.error('加载状态选项失败:', error)
    // 如果API失败，使用默认选项
    statusOptions.value = [
      { value: 'new', label: '新建' },
      { value: 'assigned', label: '已分配' },
      { value: 'in_progress', label: '处理中' },
      { value: 'resolved', label: '已解决' },
      { value: 'verified', label: '已验证' },
      { value: 'closed', label: '已关闭' },
      { value: 'reopened', label: '重新打开' }
    ]
  }
}

// 加载优先级选项
const loadPriorityOptions = async () => {
  try {
    const response = await priorityApi.getAll('defect')
    let priorities: any[] = []
    
    if (response && response.data) {
      if (response.data.success && response.data.data) {
        priorities = response.data.data
      } else if (Array.isArray(response.data)) {
        priorities = response.data
      }
    } else if (Array.isArray(response)) {
      priorities = response
    }
    
    priorityOptions.value = priorities.map((p: any) => ({
      value: p.code || p.value,
      label: p.name || p.label
    }))
  } catch (error) {
    console.error('加载优先级选项失败:', error)
    // 如果API失败，使用默认选项
    priorityOptions.value = [
      { value: 'lowest', label: '最低' },
      { value: 'low', label: '低' },
      { value: 'medium', label: '中' },
      { value: 'high', label: '高' },
      { value: 'urgent', label: '紧急' },
      { value: 'critical', label: '严重' }
    ]
  }
}

// 方法
const loadDefects = async () => {
  try {
    loading.value = true
    const params: DefectFilter = {
      page: currentPage.value,
      size: pageSize.value,
      project_id: props.projectId || undefined,
      // 如果传入版本ID数组，使用第一个版本ID进行筛选（支持多版本筛选）
      version_id: props.versionIds && props.versionIds.length > 0 ? props.versionIds[0] : undefined
    }
    
    const response = await getDefects(params)
    
    // 处理分页响应格式
    if (response && response.items) {
      defects.value = response.items as Defect[]
      total.value = response.total || 0
    } else if (Array.isArray(response)) {
      defects.value = response as Defect[]
      total.value = response.length
    } else if (response && response.data && Array.isArray(response.data)) {
      defects.value = response.data as Defect[]
      total.value = response.total || response.data.length
    } else {
      defects.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载缺陷列表失败:', error)
    ElMessage.error('加载缺陷列表失败')
    defects.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleSelectionChange = (selection: Defect[]) => {
  selectedDefects.value = selection
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadDefects()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadDefects()
}

const clearSelection = () => {
  selectedDefects.value = []
  defectTableRef.value?.clearSelection()
}

const removeDefect = (defect: Defect) => {
  const index = selectedDefects.value.findIndex(d => d.id === defect.id)
  if (index > -1) {
    selectedDefects.value.splice(index, 1)
    defectTableRef.value?.toggleRowSelection(defect, false)
  }
}

const handleClose = () => {
  visible.value = false
  clearSelection()
}

const handleConfirm = () => {
  emit('confirm', selectedDefects.value)
  handleClose()
}

// 辅助方法
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString()
}

const getDefectTypeLabelHelper = (type: string) => {
  return getDefectTypeLabel(type) || type
}

const getDefectTypeTagType = (type: string | null | undefined) => {
  if (!type) return 'info'
  const types: Record<string, string> = {
    functional: 'primary',
    ui: 'success',
    performance: 'warning',
    security: 'danger',
    compatibility: 'info',
    usability: 'info',
    data: 'info',
    integration: 'info',
    configuration: 'info',
    documentation: 'info'
  }
  return types[type] || 'info'
}

const getStatusLabel = (status: string) => {
  const statusOption = statusOptions.value.find(opt => opt.value === status)
  if (statusOption) {
    return statusOption.label
  }
  return getDefectStatusLabel(status) || status
}

const getStatusTagType = (status: string | null | undefined): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  if (!status) return 'info'
  const state = stateStore.getStateByCode(status, ModuleType.DEFECT)
  if (state) {
    // 根据颜色映射到Element Plus的tag type
    const colorMap: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
      '#67C23A': 'success',
      '#409EFF': 'primary',
      '#E6A23C': 'warning',
      '#F56C6C': 'danger',
      '#909399': 'info'
    }
    return colorMap[state.color] || 'info'
  }
  // 默认映射
  const types: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
    new: 'info',
    assigned: 'warning',
    in_progress: 'primary',
    resolved: 'success',
    verified: 'success',
    closed: 'info',
    reopened: 'danger'
  }
  return types[status] || 'info'
}

const getPriorityLabel = (priority: string) => {
  const priorityOption = priorityOptions.value.find(opt => opt.value === priority)
  if (priorityOption) {
    return priorityOption.label
  }
  return getDefectPriorityLabel(priority) || priority
}

const getPriorityTagType = (priority: string | null | undefined): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  if (!priority) return 'info'
  const types: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
    lowest: 'info',
    low: 'info',
    medium: 'info',
    high: 'warning',
    urgent: 'danger',
    critical: 'danger',
    blocker: 'danger'
  }
  return types[priority] || 'info'
}

const getSeverityLabel = (severity: string) => {
  return getDefectSeverityLabel(severity) || severity
}

const getSeverityTagType = (severity: string | null | undefined): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  if (!severity) return 'info'
  const types: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
    trivial: 'info',
    minor: 'info',
    major: 'warning',
    important: 'danger',
    critical: 'danger',
    urgent: 'danger',
    blocker: 'danger'
  }
  return types[severity] || 'info'
}

// 监听器
watch(visible, (newVal) => {
  if (newVal) {
    loadStatusOptions()
    loadPriorityOptions()
    loadDefects()
    // 如果有预选的缺陷ID，设置选中状态
    if (props.selectedDefectIds.length > 0) {
      // 延迟执行，确保表格已渲染
      setTimeout(() => {
        const preSelectedDefects = defects.value.filter(defect => 
          props.selectedDefectIds.includes(defect.id)
        )
        selectedDefects.value = preSelectedDefects
        preSelectedDefects.forEach(defect => {
          defectTableRef.value?.toggleRowSelection(defect, true)
        })
      }, 100)
    }
  }
})

// 生命周期
onMounted(() => {
  if (visible.value) {
    loadStatusOptions()
    loadPriorityOptions()
    loadDefects()
  }
})
</script>

<style scoped>
.defect-selector-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
  }
  
  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
  
  .dialog-content {
    .filter-section {
      margin-bottom: 20px;
      padding: 16px;
      background: #f5f7fa;
      border-radius: 8px;
      
      :deep(.el-input__wrapper) {
        border-radius: 6px;
      }
      
      :deep(.el-select .el-input__wrapper) {
        border-radius: 6px;
      }
    }
    
    .defect-list {
      margin-bottom: 20px;
      
      :deep(.el-table) {
        border-radius: 8px;
        overflow: hidden;
      }
      
      :deep(.el-table__header) {
        background-color: #f5f7fa;
      }
      
      :deep(.el-table th) {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
      }
      
      .defect-title {
        display: flex;
        align-items: center;
        
        .ml-2 {
          margin-left: 8px;
        }
      }
    }
    
    .pagination-section {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
      padding: 12px 0;
    }
    
    .selected-section {
      border-top: 2px solid #409eff;
      padding-top: 20px;
      background: #f5f7fa;
      padding: 16px;
      border-radius: 8px;
      margin-top: 16px;
      
      .selected-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        font-weight: 600;
        color: #303133;
        font-size: 15px;
        
        .el-button {
          color: #409eff;
          
          &:hover {
            color: #66b1ff;
          }
        }
      }
      
      .selected-list {
        max-height: 120px;
        overflow-y: auto;
        
        .selected-tag {
          margin-right: 8px;
          margin-bottom: 8px;
          border-radius: 4px;
          padding: 4px 12px;
          font-size: 13px;
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid #ebeef5;
    
    .el-button {
      min-width: 100px;
      border-radius: 6px;
    }
  }
}

.text-gray-400 {
  color: #909399;
}
</style>

